package com.neardrug.utils;

import org.openscience.cdk.DefaultChemObjectBuilder;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.fingerprint.CircularFingerprinter;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IChemObjectBuilder;
import org.openscience.cdk.isomorphism.Pattern;
import org.openscience.cdk.similarity.Tanimoto;
import org.openscience.cdk.smarts.SmartsPattern;
import org.openscience.cdk.smiles.SmilesParser;

import java.util.BitSet;

/**
 * @author rui
 * @ClassName: ChemicalUtil
 * @create 2023-06-30 19:40
 */
public class ChemicalUtil {

    private static IChemObjectBuilder builder = DefaultChemObjectBuilder.getInstance();
    private static SmilesParser sp = new SmilesParser(builder);
    public static double getSimilarity(String smiles1,String smiles2) throws CDKException {
        IAtomContainer molecule1 = sp.parseSmiles(smiles1);
        IAtomContainer molecule2 = sp.parseSmiles(smiles2);
        CircularFingerprinter fp = new CircularFingerprinter(4);
        BitSet fp1 = fp.getFingerprint(molecule1);
        BitSet fp2 = fp.getFingerprint(molecule2);
        return Tanimoto.calculate(fp1, fp2);
    }

    public static Boolean isSubStructure(String smiles1,String smiles2) throws CDKException {
        IAtomContainer molecule1 = sp.parseSmiles(smiles1);
        IAtomContainer molecule2 = sp.parseSmiles(smiles2);
        Pattern pattern = SmartsPattern.findSubstructure(molecule1);
        return pattern.matches(molecule2);
    }

}
